package com.szgd.controller;

import com.szgd.service.personnel.AttachService;
import com.szgd.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/upload")
public class UploadController extends BaseController  {
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;
    private static Logger logger = Logger.getLogger(UploadController.class);


    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile[] updateFiles) {

        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            for (MultipartFile file : updateFiles) {
                String date = df.format(new Date());
                uploadFileNameList.add(fileUtil.uploadFile(file.getInputStream(),file.getOriginalFilename(),date));
            }
            return getSuccMap(uploadFileNameList);
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("上传失败！-------"+e.getMessage());
        }
    }

    @RequestMapping(value = "/uploadFileWithName", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadFileWithName(@RequestParam("file") MultipartFile[] updateFiles,@RequestParam("name") String name,@RequestParam("idNumber") String idNumber) {

        try {


            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            for (MultipartFile file : updateFiles) {
                String fileName = file.getOriginalFilename();
                int index =  fileName.lastIndexOf(".");
                String suffix = fileName.substring(index+1,fileName.length());
                fileName = name +"_"+ idNumber+"."+suffix;
                String date = df.format(new Date());
                uploadFileNameList.add(fileUtil.uploadFile(file.getInputStream(),fileName,date));
            }
            return getSuccMap(uploadFileNameList);
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("上传失败！-------"+e.getMessage());
        }
    }

    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String subPath = URLDecoder.decode(request.getParameter("path"),"UTF-8");
        String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String fileAbsolutePath = fileUploadPath + File.separator + subPath +  File.separator + fileName;
        File file = new File(fileAbsolutePath);
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer;
        buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 设置response的Header
        //String fileName = file.getName();
        //fileName = URLEncoder.encode(fileName,"UTF-8");
        fileName = new String(fileName.getBytes(),"ISO8859-1");
        long fileLength = file.length();
        response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
        response.addHeader("Content-Length", "" + String.valueOf(fileLength));
        response.setContentType("application/octet-stream");    //自动匹配文件类型
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping(value = "/downloadUserFile", method = RequestMethod.GET)
    public void downloadUserFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
        String userFiledPath = PropertiesUtil.get("userFilePath");
        String fileAbsolutePath = userFiledPath + File.separator + fileName;
        File file = new File(fileAbsolutePath);
        if (!file.exists())
        {
            response.setContentType("text/html;character=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("暂不提供该文件下载！");
            pw.flush();
            pw.close();
        }else
        {
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer;
            buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();

            fileName = new String(fileName.getBytes(),"ISO8859-1");
            long fileLength = file.length();
            response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Content-Length", "" + String.valueOf(fileLength));
            response.setContentType("application/octet-stream");    //自动匹配文件类型
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }

    }

    /*
     * 在线预览图片
     */
    @RequestMapping(value = "/previewPic", method = RequestMethod.GET)
    public void previewPic(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String subPath = URLDecoder.decode(request.getParameter("path"),"UTF-8");
        String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String fileAbsolutePath = fileUploadPath + File.separator + subPath +  File.separator + fileName;
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        FileInputStream fis = new FileInputStream(fileAbsolutePath);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }

    /*
     * 在线预览图片
     */
    @RequestMapping(value = "/previewSnapImage", method = RequestMethod.GET)
    public void previewSnapImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String subPath = URLDecoder.decode(request.getParameter("path"),"UTF-8");
        String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
        String fileUploadPath = PropertiesUtil.get("snapImagePath");
        String fileAbsolutePath = fileUploadPath + File.separator + subPath +  File.separator + fileName;
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        FileInputStream fis = new FileInputStream(fileAbsolutePath);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }

    @RequestMapping(value = "/downloadSnapImage", method = RequestMethod.GET)
    public void downloadSnapImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String subPath = URLDecoder.decode(request.getParameter("path"),"UTF-8");
        String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
        String fileUploadPath = PropertiesUtil.get("snapImagePath");
        String fileAbsolutePath = fileUploadPath + File.separator + subPath +  File.separator + fileName;
        File file = new File(fileAbsolutePath);
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer;
        buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 设置response的Header
        //String fileName = file.getName();
        //fileName = URLEncoder.encode(fileName,"UTF-8");
        fileName = new String(fileName.getBytes(),"ISO8859-1");
        long fileLength = file.length();
        response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
        response.addHeader("Content-Length", "" + String.valueOf(fileLength));
        response.setContentType("application/octet-stream");    //自动匹配文件类型
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping(value = "/downloadErrorRecord")
    public void downloadErrorRecord(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String path = getParam(request, "path");
        path = URLDecoder.decode(path,"UTF-8");
        try {
            String realPath = request.getServletContext().getRealPath(path);
            this.download(response, realPath);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String classpathString = this.getClass().getClassLoader().getResource("/").toString();
        classpathString = StringUtils.replace(classpathString, "file:", "");
        String templateName = URLDecoder.decode(request.getParameter("templateName"),"UTF-8");
        String templatePath = classpathString + "/template/"+templateName;

        try {
            this.download(response, templatePath);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/downloadByAttachId")
    public void downloadByAttachId(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String id = getParam(request, "id");
        Map<String, Object> attachMap = attachService.getAttach(id);
        String fullPath = fileUploadPath + File.separator + attachMap.get("path")+ File.separator +  attachMap.get("name");
        try {
            this.download(response, fullPath);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

}
